package com.guaoran.source.rmi.rcp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/13 14:22
 */
public class TCPTransport {
    private String host;
    private int port;

    public TCPTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 创建一个连接，进行服务端网络通信
     * @return
     */
    private Socket newSocket(){
        System.out.println("创建一个新的连接");
        Socket socket = null;
        try {
            socket = new Socket(host,port);
            return socket;
        } catch (Exception e) {
            throw new RuntimeException("连接建立失败");
        }
    }

    /**
     * 发送请求消息
     *   将请求的参数信息序列化后，发送到服务端
     * @param rpcRequest
     * @return
     */
    public Object send(RpcRequest rpcRequest){
        Socket socket = null;
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        try {
            socket = newSocket();
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(rpcRequest);
            outputStream.flush();
            inputStream = new ObjectInputStream(socket.getInputStream());
            Object object = inputStream.readObject();
            return object;
        }catch (Exception e){
             throw new RuntimeException("发送消息失败");
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
